// @flow
import React from 'react'
import { Form, Input, Button, message, TreeSelect } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { saveUserMenu } from 'store/modules/menu'
import { connect } from 'react-redux'
const FormItem = Form.Item
const SHOW_PARENT = TreeSelect.SHOW_PARENT
import styles from './MenuEdit.css'
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}

type Props = {
  history: Object,
  saveUserMenu: Function,
  form: Object
}

type State = {
  loading: boolean,
  taskData: Object,
  value: Object,
  menus: Array<Object>
}

class MenuEdit extends React.Component {
  props: Props
  state: State
  submit: Function
  goBack: Function
  initChildren: Function
  getMenus: Function
  onChange: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      loading: false,
      taskData: {},
      value: {},
      menus: []
    }

    this.submit = this.submit.bind(this)
    this.goBack = this.goBack.bind(this)
    this.onChange = this.onChange.bind(this)
    this.getMenus = this.getMenus.bind(this)
  }

  componentWillMount () {
    this.getMenus()
    const { data } = this.props.history.location.state
    this.setState({
      taskData: data,
      value: data.parentId
    })
  }

  submit () {
    const { form } = this.props
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        loading: true
      })
      const values = {
        ...fieldsValue
      }
      const { taskData } = this.state
      universalFetch(`${__SERVICE_API__}sys/menus/${taskData.id}`,
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JSON.stringify(values)
        })
        .then((res) => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          this.setState({
            loading: false
          })
          message.success('修改成功')
          // this.getUserMenu(taskData.id)
          this.props.history.push('/system')
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
          message.error('修改失败')
          this.setState({
            loading: false
          })
        })
    })
  }
  goBack () {
    this.props.history.push('/system')
  }
  onChange (value) {
    this.setState({ value })
  }
  initChildren (object) {
    const children = object.children.map((data, index) => {
      let data1 = {}
      data1['key'] = object.key + '-' + index + ''
      data1['value'] = data.id + ''
      data1['label'] = data.name + ''
      data1['children'] = data.children
      this.initChildren(data1)
      return data1
    })
    object['children'] = children
  }
  getMenus () {
    universalFetch(`${__SERVICE_API__}sys/menus?isTree=true`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          menus:json.result.map((data, index) => {
            let data1 = {}
            data1['key'] = '0' + '-' + index + ''
            data1['value'] = data.id + ''
            data1['label'] = data.name + ''
            data1['children'] = data.children
            this.initChildren(data1)
            return data1
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getUserMenu (userId: number) {
    const { saveUserMenu } = this.props
    universalFetch(`${__SERVICE_API__}sys/users/${userId}/menus?isTree=true`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        saveUserMenu(json.result)
        // this.props.history.push('/system')
        // this.props.history.push('/login')
        //
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const { taskData, loading, value, menus } = this.state
    const tProps = {
      treeData: menus,
      value: value,
      onChange: this.onChange,
      multiple: false,
      treeCheckable: false,
      treeDefaultExpandAll: true,
      showCheckedStrategy: SHOW_PARENT,
      placeholder: '请选择父菜单',
      searchPlaceholder: 'Please select',
      style: {
        width: 300
      }
    }
    return (
      <div className={styles['main']}>
        <Form>
          <FormItem {...formItemLayout} label='上级菜单' hasFeedback

            >
            {
              getFieldDecorator('parentId', {
                initialValue: taskData.parentId.toString(),
                rules: [
                  { required: true, message: '请填写父级菜单', whitespace: true }
                ]
              })(
                <TreeSelect {...tProps} />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='名称' hasFeedback>
            {
              getFieldDecorator('name', {
                rules: [
                  { required: true, message: '请填写名称', whitespace: true }
                ],
                initialValue: taskData.name
              })(
                <Input placeholder='请填写名称' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='链接' hasFeedback>
            {
              getFieldDecorator('href', {
                rules: [
                  { required: true, message: '请填写链接', whitespace: true }
                ],
                initialValue: taskData.href
              })(
                <Input placeholder='请填写链接' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='目标' hasFeedback>
            {
              getFieldDecorator('target', {
                rules: [
                  { required: false, message: '链接地址打开的目标窗口，默认：mainFrame' }
                ],
                initialValue: taskData.target
              })(
                <Input placeholder='链接地址打开的目标窗口，默认：mainFrame' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='图标' hasFeedback>
            {
              getFieldDecorator('icon', {})(
                <Input placeholder='请填写图标' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='排序' hasFeedback>
            {
              getFieldDecorator('sort', {
                initialValue: taskData.sort
              })(
                <Input placeholder='请填写排序' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='可见' hasFeedback>
            {
              getFieldDecorator('isShow', {
                initialValue: taskData.isShow
              })(
                <Input placeholder='' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='权限标识' hasFeedback>
            {
              getFieldDecorator('permission', {
                rules: [
                  { required: false, message: '权限标识' }
                ],
                initialValue: taskData.permission
              })(
                <Input placeholder='' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='备注' hasFeedback>
            {
              getFieldDecorator('remarks', {
                rules: [
                  { required: false, message: '备注' }
                ],
                initialValue: taskData.remarks
              })(
                <Input placeholder='' />
              )
            }
          </FormItem>
          <FormItem
            {...tailFormItemLayout}
          >
            <Button type='primary'
              className='login-form-button'
              onClick={this.submit}
              loading={loading}
              >
              提交
            </Button>
            <Button style={{ marginLeft: '20px' }}
              onClick={() => {
                this.props.history.push('/system')
              }}
              >
              返回
            </Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {}
}
export default connect(mapStatesToProps, { saveUserMenu })(Form.create({})(MenuEdit))
